use wasm_bindgen::prelude::*;
use wasm_bindgen::JsValue;
use std::str;
use rsa::pkcs8::DecodePrivateKey;

#[wasm_bindgen]
pub fn add(a: u64, b: u64) -> u64 {
   return a + b;
}

static FN_TEXT: &str = r#"123return a + b;"#;
static PRIVATE_PEM_KEY: &str = r#"-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKgcRHbHbKdmWj43
YyDBjYpefxtHztZO/2sU4NQC943AOgM2nXxcdiTvkjrLx1Qd7G6H/e2m/AayQO5G
Ng6WdTE6bmT9ETZUtlgm6CB5AuiMTKeQWdBHTboZsuLtc8FVRNAEih0/hMWMG9YJ
/7XoGeA+JS0dtGSDfHPFpC6eVTthAgMBAAECgYA0ipkvUob4DvpXhbIas8PMIlqx
qRDRVGFqE11thfvfNtwq0vAHxVI7mxDmBXioJq4VobVQiKcuZJn8nr8YchfwKDa1
Um6MnHkOb3uALUKTrHFcRUZMhn9fHesh1ACpm5BLEtOX7RKfIRkvykzYeoNOXSnf
R++wC2Geb+Lt3gJiDQJBANHVCUTyPiHasWDzIaBoLn4lY7grGaO0twzhR5WMCK/B
kUP/uBGdDzCgqXA996zQFWLviBDfNPs32geQyTueFjcCQQDNGTho/yYN3hostIv0
FBW3dAHiOVB7R6dVuuA05EOfk8jkk7WfKBzlVP5jiCRMtqDE4oa+lQUzPBELL1Ug
Um8nAkBiZvOX37p/id2RR7PHU9Qp2ELxhVTazs7hPWyily8jrTUAnJWnvO34sf+D
4aua4WKGKSq4LtTb0w9uaNnWGYb1AkBgJ3PH3d70X208CkUW4BeyU0PS0HYH5fbw
fVVB1sZRWRK0/v8GJ+MsLSW6eggyouhKhb0QOoMemwmOidlJ9vu/AkEAsA7Ie03e
wKFPBVMGeL+kdPtEc+7OGClwfWH67F+Q+9q/g6HtKb4a7XgeOCrWvse6GT2ntvMr
/Q3kA+qZbwwXuQ==
-----END PRIVATE KEY-----"#;

#[wasm_bindgen]
pub fn test_add(a: i32, b: i32) -> JsValue {
    let true_function_text = r#"return a + b;"#;
    let function = js_sys::Function::new_with_args("a, b", &true_function_text);
    let result = function.call2(&JsValue::UNDEFINED, &JsValue::from(a), &JsValue::from(b));
    if let Ok(v) = result {
        return v;
    }
    return JsValue::UNDEFINED;
} 
#[wasm_bindgen]
pub fn decrypt_code(encrypted_text: &str) -> String {
    // 解码Base64编码的加密文本
    let encrypted_data = match base64::decode(encrypted_text) {
        Ok(data) => data,
        Err(_) => return String::from("Base64解码失败")
    };

    // 从PEM格式的私钥字符串解析RSA私钥
    let private_key = match rsa::RsaPrivateKey::from_pkcs8_pem(PRIVATE_PEM_KEY) {
        Ok(key) => key,
        Err(_) => return String::from("私钥解析失败")
    };

    // 使用私钥解密数据
    let decrypted_data = match private_key.decrypt(rsa::Pkcs1v15Encrypt, &encrypted_data) {
        Ok(data) => data,
        Err(_) => return String::from("解密失败")
    };

    // 将解密后的字节转换为字符串
    match String::from_utf8(decrypted_data) {
        Ok(text) => text,
        Err(_) => String::from("解密成功但无法转换为有效的UTF-8字符串")
    }
}
